<template>
    <div class="page-container">
        <!--针对页面样式颜色等作出修改-->
        <!--可使用scss全局样式改变-->
        <!--对照片墙的三张轮播图进行设置-->
        <el-divider content-position="left">
            <el-tag>设置一：</el-tag>
        </el-divider>
        <el-input placeholder="请输入图片地址" v-model="input" class="input-with-select">
            <el-select v-model="select" slot="prepend" placeholder="请选择">
                <el-option label="轮播图1" value="1"></el-option>
                <el-option label="轮播图2" value="2"></el-option>
                <el-option label="轮播图3" value="3"></el-option>
            </el-select>
            <el-button slot="append" icon="el-icon-picture" @click="updatePic"></el-button>
        </el-input>
        <el-divider content-position="left">
            <el-tag>设置二：</el-tag>
        </el-divider>
        <div class="block">
            <el-slider
                    v-model="value"
                    vertical
                    height="200px">
            </el-slider>
        </div>
        <br>
        <el-button @click="update">检测更新</el-button>
    </div>
</template>

<script>
    import Service from "../../../common/Service";
    import {mapState} from 'vuex';

    // let {app} = require('electron').remote;
    //
    // let fs = require('fs');
    // let unzip = require("unzipper");
    // let request = require('request');
    // let progress = require('request-progress');
    // let {spawnSync} = require("child_process");
    //
    // function getSavePath() {
    //     if ('production' === process.env.NODE_ENV) {
    //         console.log("production")
    //     }
    //     let path = app.getAppPath().replace("app.asar", "") + "update.zip";
    //     // console.log("Update file save path is: " + path);
    //     return path;
    // }
    //
    // function uncompress(path) {
    //     let targetPath = path.replace("update.zip", "update");
    //     process.noAsar = true;
    //     fs.createReadStream(path).pipe(unzip.Extract({
    //         path: targetPath
    //     })).on("close", () => {
    //         console.log("zxc")
    //         onUncompress(targetPath + "\\app.asar", path.replace("update.zip", ""));
    //     })
    // }
    //
    // function onUncompress(src, dist) {
    //     console.log("dist=" + dist);
    //     console.log("src=" + src);
    //     if ('win32' === progress.platform) {
    //         // Windows下 app.asar被占用无权限
    //     } else {
    //         // linux环境下的更新
    //         // replaceAppInLinux(src, dist);
    //     }
    // }
    //
    // function replaceAppInLinux(src, dist) {
    //     spawnSync("bash", ["-c", ["cd " + dist, `mv -f ${src} ${dist}`].join(" && ")]);
    //     setTimeout(() => {
    //         onSuccess();
    //     }, 3000)
    // }
    //
    // function onSuccess() {
    //     console.log("成功升级");
    //     app.relaunch();
    //     app.exit(0);
    // }
    const {app, dialog} = require('electron').remote;
    const EAU = require('electron-asar-hot-updater');

    export default {
        name: "PageSetting",
        data() {
            return {
                input: '',
                select: '',
                value: 0
            }
        },
        computed: mapState(["user"]),
        methods: {
            //FIXME 更新代码问题：打包之后app.asar内的模块丢失，并未一起打包到里面（暂未解决）
            //FIXME 试试其它更新解决方案：http://blog.joylau.cn/2019/09/16/Electron-AutoUpdater/
            // 更新代码
            update() {
                // let url = "http://39.102.68.23:80/";
                let url = "http://localhost:3000/update";
                EAU.init({
                    'api': url, // The API EAU will talk to
                    'server': false, // Where to check. true: server side, false: client side, default: true.
                    'debug': false, // Default: false.
                    'headers': {Authorization: 'token'}, // Default: {}
                    'body': {
                        name: "update",
                        current: "0.1.0"
                    }, // Default: name and the current version
                    'formatRes': function (res) {
                        return res
                    } // 对返回的数据进行格式化操作的回调函数，保证EAU可以正常操作操作数据。比如格式化后返回：{version: xx, asar: xx}
                });
                EAU.check(function (error, last, body) {
                    console.log(last);
                    console.log(body);
                    if (error) {
                        if (error === 'no_update_available') {
                            return false;
                        }
                        dialog.showErrorBox('info', error);
                        return false;
                    }
                    EAU.progress(function (state) {
                        // The state is an object that looks like this:
                        // {
                        //     percent: 0.5,
                        //     speed: 554732,
                        //     size: {
                        //         total: 90044871,
                        //         transferred: 27610959
                        //     },
                        //     time: {
                        //         elapsed: 36.235,
                        //         remaining: 81.403
                        //     }
                        // }
                    });
                    EAU.download((error) => {
                        if (error) {
                            dialog.showErrorBox('info', error);
                            return false
                        }
                        console.log("下载好了");
                        console.log(process.platform);
                        if (process.platform === 'darwin') {
                            app.relaunch();
                            app.quit()
                        } else {
                            app.quit()
                        }
                    })
                })

                // progress(request(url), {}).on('progress', state => {
                //     console.log('progress', state);
                // }).on('error', err => {
                //     console.log(err);
                // }).on('end', () => {
                //     // console.log(getSavePath())
                //     uncompress(getSavePath());
                // }).pipe(fs.createWriteStream(getSavePath()));
            },
            // 更新图片
            updatePic() {
                if (this.input === "" || this.select === "") {
                    this.$message("填写一条记录");
                    return;
                }
                if (this.user.user_id === null) {
                    this.$message("请登录后执行此操作");
                    return;
                }
                Service.base.updatePic(this.input, this.select, this.user.user_id).then(data => {
                    console.log(data)
                })
            }
        }
    }
</script>
<style>
    .el-select .el-input {
        width: 130px;
    }

    .input-with-select .el-input-group__prepend {
        background-color: #fff;
    }

    .el-divider--horizontal {
        display: inline-block;
    }
</style>
<style scoped lang="scss">
    .page-container {
        width: 100%;
        height: 100%;
    }
</style>